package view;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;

public class HintTextArea extends TextArea {

    private String mHint = "";

    public HintTextArea(){
        super();

        this.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                cleanHint();
            }
        });

        this.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                cleanHint();
            }
        });

        this.focusedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
                if (oldValue&&!newValue&&getLength()==0&&!mHint.isEmpty()){
                    setHint(mHint);
                }
            }
        });
    }

    private void cleanHint(){
        if (mHint.isEmpty()){
            return;
        }

        if (getText().equals(mHint)){
            clear();
            setStyle("-fx-text-fill: #000000");
        }
    }

    public boolean isEmpty(){
        if (getLength() == 0){
            return true;
        }

        if (mHint.isEmpty()){
            return false;
        }

        return mHint.equals(getText());
    }

    public void setHint(String hint){
        this.mHint = hint;
        this.setText(mHint);
        this.setStyle("-fx-text-fill: #008B8B");
    }
}
